package org.or5e.service.core.ds;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.or5e.core.BaseObject;
import org.or5e.service.core.ds.event.EventDataSource;
import org.or5e.service.core.ds.event.EventDataSourceImpl;
import org.or5e.service.core.ds.fm.FriendMasterDataSource;
import org.or5e.service.core.ds.fm.FriendMasterImpl;
import org.or5e.service.core.ds.login.LoginDataSource;
import org.or5e.service.core.ds.login.LoginDataSourceImpl;
import org.or5e.service.core.ds.wm.WishMasterDataSource;
import org.or5e.service.core.ds.wm.WishMasterDataSourceImpl;
import org.or5e.service.core.sm.SessionManager;
import org.or5e.service.core.sm.SessionManagerSPI;

public class DataSourceFactory extends BaseObject {
	private SessionFactory _sessionFactory = null;
	private SessionManager _sessionManager = null;
	private LoginDataSourceImpl _loginDS = null;
	private FriendMasterDataSource _fMaster = null;
	private WishMasterDataSource _wMaster = null;
	private static DataSourceFactory _dsFactory = null;
	static {
		_dsFactory = new DataSourceFactory();
	}
	private DataSourceFactory() {
		_sessionFactory = new Configuration().configure().buildSessionFactory();
		_sessionManager = new SessionManagerSPI();
		_sessionManager.init();
		
		//Adding shutdown hook so that the resource gets cleaned off
//		Runtime.getRuntime().addShutdownHook(new Thread() {
//			public void run() {
//				info("Shutting down Data Source.");
//				_sessionFactory.close();
//				_sessionManager.destroy();
//			}
//		});
	}
	public Object getDataSource(Class<? extends DataSource> t){
		if(t == EventDataSource.class){
			return new EventDataSourceImpl(this._sessionFactory, this._sessionManager);
		}
		
		else if(t == LoginDataSource.class) {
			if(_loginDS == null) {
				_loginDS = new LoginDataSourceImpl(this._sessionFactory, this._sessionManager);
				_loginDS.initilizeDataSource();
			}
			return _loginDS;
		}
		else if(t == FriendMasterDataSource.class) {
			if(_fMaster == null) {
				_fMaster = new FriendMasterImpl(this._sessionFactory, this._sessionManager);
				_fMaster.initilizeDataSource();
			}
			return _fMaster;
		}
		else if(t == WishMasterDataSource.class) {
			if(_wMaster  == null) {
				_wMaster = new WishMasterDataSourceImpl(this._sessionFactory, this._sessionManager);
				_wMaster.initilizeDataSource();
			}
			return _wMaster;
		}
		return null;
	}

	public static DataSourceFactory getDataSourceFactory() {
		return _dsFactory;
	}
	@Override
	public String getName() {
		return "DataSourceFactory";
	}
	public static void main(String[] args) {
		System.out.println("Test Data");
	}
}